const { ethers, network } = require("hardhat")
const fs = require("fs")
const frontendlocaltion =
    "../nftshop-frontent-nextjs/constant/networkUpdateHook.json"

module.exports = async function () {
    if (process.env.UPDATE_FRONTEND) {
        console.log("updating data to frontend")
        await updateContractAndAddress()
    }
}

async function updateContractAndAddress() {
    const NFTSHOP = await ethers.getContract("NFTSHOP")
    const contractAddress = JSON.parse(
        fs.readFileSync(frontendlocaltion, "utf-8")
    )
    // @ts-ignore
    const chainId = network.config.chainId.toString()
    if (chainId in contractAddress) {
        if (!contractAddress[chainId]["NFTSHOP"].includes(NFTSHOP.address)) {
            contractAddress[chainId]["NFTSHOP"].push(NFTSHOP.address)
        }
    } else {
        contractAddress[chainId] = { NFTSHOP: [NFTSHOP.address] }
    }
    fs.writeFileSync(frontendlocaltion, JSON.stringify(contractAddress))
}

module.exports.tags = ["all", "update"]
